import os
import shutil
import tempfile

# 1.创建临时文件
try:
    # file=tempfile.mkstemp()
    fd,name=tempfile.mkstemp(suffix=".log",prefix="text")
    with os.fdopen(fd,"w") as fp:
        fp.write("hello world")
    print(f"tempfile={name}")
finally:
    # os.close(fp)      --> fdopen(fd,"") as fp结束时,已调用close
    os.remove(name)

# 2.创建临时目录
temp_dir=tempfile.mkdtemp(".log","test-")   # /tmp/test-xqistwk6.log
try:
    with open(f"{temp_dir}/temp_file.txt","w") as fp:
          fp.write('hello world')
finally:
    shutil.rmtree(temp_dir)
    
    
""" 总结
tempfile.mkstemp() 创建临时文件, 需要手动 close, remove
tempfile.mkdtemp() 创建的临时目录, 需要手动删除

推荐看实例: 3_tempfile_TemporaryDirectory_临时目录.py

"""